import React, { useEffect, useState } from 'react'
import { Col, Form, Input, Button, Table, Modal, InputNumber, message, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import {
  fetchComponyList,
  addCompony,
  delCompony,
} from '@/services/setting/trans'
import { formItemLayout } from '@/utils/utils'

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))

const columns = [
  {
    title: '物流公司',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '快递100code',
    dataIndex: 'expressageCode',
    key: 'expressageCode',
  },
  {
    title: '淘宝code',
    dataIndex: 'taobaoCode',
    key: 'taobaoCode',
  },
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
  },
];

const Compony = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [data, setTransList] = useState([])
  const [record, setRecord] = useState([])
  const [param, setParam] = useState({
    expressageCode: null,
    name: null,
    taobaoCode: null,
  })
  const [isShow, setIsShow] = useState(false)

  useEffect(() => {
    init()
  }, [])

  const init = async (params = param) => {
    const res = await fetchComponyList({
      logisticsCompany: params,
    })
    setTransList(res.data)
  }

  const addData = async params => {
    const res = await addCompony({
      logisticsCompany: params
    })
    res.code == 0 && init()
    message.info(res.msg)
    setIsShow(!isShow)
  }

  const delData = async params => {
    const res = await delCompony(params)
    res.code == 0 && setTransList(() => {
      data.splice(data.findIndex(v => v.id == params.id), 1)
      return [...data]
    })
    message.info(res.msg)
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      init({
        name: values.cname,
        expressageCode: values.cexpressageCode,
        taobaoCode: values.ctaobaoCode,
      })
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
    init()
  }
  // 查询条件
  const getFields = () => {
    return(
      <>
        <Col span={6}>
          <Form.Item label={`名称`}>
            {getFieldDecorator(`cname`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label={`快递100code`}>
            {getFieldDecorator(`cexpressageCode`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label={`淘宝code`}>
            {getFieldDecorator(`ctaobaoCode`, {})
              (<Input />)}
          </Form.Item>
        </Col>
      </>
    )
  }
  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      // add
      case 1:
        return setIsShow(!isShow) 
      // del
      case 4:
        return delData({id: record[0].id})
      default:
        break;
    }
    
  }
  const handleSubmit = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      addData({
        ...values
      })
    })
  }

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setRecord(selectedRows)
    },
  };

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowSelection={rowSelection}
        rowKey={record => record.id}
      />
       <Modal
        title="新增"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={() => setIsShow(!isShow)}
        destroyOnClose
        okText={'新增'}
        cancelText={'取消'}
      >
        <Form {...formItemLayout}>
          {
            columns.filter(i => i.key != 'sort').map(u => (
              <Form.Item label={u.title} key={u.key}>
                {getFieldDecorator(u.key, {
                  rules: [
                    {
                      required: true,
                      message: `请输入${u.title}`
                    },
                  ],
                })(<Input />)}
              </Form.Item>
            ))
          }
          <Form.Item label='排序'>
            {getFieldDecorator('sort', {
              rules: [
                {
                  required: true,
                  message: '请输入数字'
                },
              ],
            })(<InputNumber min={0} />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
    )
}

export default Form.create()(Compony)
